package CGW.service;

import CGW.bean.Page;
import CGW.bean.User;
import CGW.dao.UserDao;

import java.util.List;

public class UserService {
    private UserDao dao;

    public UserService(UserDao dao) {
        this.dao = dao;
    }

    public List<User> queryAll(){
        List<User> ret = dao.all(1, 100);
        dao.close();
        return ret;
    }

    public Page<User> queryAll(int page, int pageSize){
        int total = dao.total();
        List<User> ret = dao.all(page, pageSize);
        Page<User> pageBean = new Page<>(ret, page, (int)Math.ceil(total*1.0/pageSize), pageSize);
        dao.close();
        return pageBean;
    }

    public User get(int user_id){
        User u = dao.get(user_id);
        dao.close();
        return u;
    }

    public boolean insert(User user){
        int rows = dao.add(user);
        dao.commit();
        dao.close();
        return rows > 0;
    }

    public boolean update(User user){
        int rows = dao.update(user);
        dao.commit();
        dao.close();
        return  rows > 0;
    }
    public boolean delete(int user_id){
        int rows = dao.delete(user_id);
        dao.commit();
        dao.close();
        return  rows > 0;
    }

    public User login(String name, String pwd){
        User user = dao.login(name, pwd);
        dao.close();
        return user;
    }

    public void close(){
        dao.close();
    }
}